/**
 * Created by tums on 13/8/15.
 */
import {Promise} from 'es6-promise';

let _callbacks = [];
let _promises = [];

let Dispatcher = {
    register(callback) {
        _callbacks.push(callback);
        return _callbacks.length - 1;
    },

    dispatch(payload) {
        let resolves = [];
        let rejects = [];
        _promises = _callbacks.map(function (_, i) {
            return new Promise(function (resolve, reject) {
                resolves[i] = resolve;
                rejects[i] = reject;
            });
        });

        _callbacks.forEach(function (callback, i) {
            Promise.resolve(callback(payload))
                .then(function () {
                    resolves[i](payload);
                }, function () {
                    rejects[i](new Error('Dispatcher callback unsuccessful'));
                });
        });

        _promises = [];
    }
};

export {Dispatcher as default };